package com.maxima.attendance.daos;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.maxima.attendance.pojos.Holiday;
import com.maxima.attendance.utils.DateOperations;
import com.maxima.attendance.utils.HibernateUtils;

public class HolidayDAO {
	public Holiday add(Holiday holiday) {
		Session session = HibernateUtils.getSession();
		session.beginTransaction();
		session.save(holiday);
		session.getTransaction().commit();
		session.close();
		return holiday;
	}

	@SuppressWarnings("unchecked")
	public List<Holiday> getAllHolidays() {
		Session session = HibernateUtils.getSession();
		session.beginTransaction();
		List<Holiday> holidays = null;
		try {
			holidays = (List<Holiday>) session.createQuery("select h from Holiday h order by h.date").list();
		}
		catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		session.close();
		return holidays;
	}

	public Holiday getHoliday(Integer id) {
		Session session = HibernateUtils.getSession();
		session.beginTransaction();
		Holiday holiday = null;
		try {
			holiday = (Holiday) session.createQuery("select h from Holiday h where h.id=" + id).uniqueResult();
		}
		catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		session.close();
		return holiday;
	}

	public void update(Holiday existingHoliday) {
		Session session = HibernateUtils.getSession();
		session.beginTransaction();
		Holiday holiday = null;
		try {
			holiday = (Holiday) session.createQuery("select h from Holiday h where h.id=" + existingHoliday.getId()).uniqueResult();
			holiday.setDate(existingHoliday.getDate());
			holiday.setDescription(existingHoliday.getDescription());
		}
		catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		session.close();
	}

	public boolean checkIfAlreadyPresent(Date date) {
		Session session = HibernateUtils.getSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(Holiday.class);
		criteria.add(Restrictions.eq("date", DateOperations.setZeroTime(date)));
		Integer x = criteria.list().size();
		session.close();
		return x != 0;
	}
}
